package com.sunrise.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author: liansen
 * @Date: 2024-02-07  12:49
 */
@Slf4j
public class JsonUtils {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 将json字符串转换为对象
     * @param jsonStr json数据
     * @param typeReference 使用复杂类型的时候使用typeReference
     * @return T
     * @param <T> 泛型
     */
    public static <T> T parseObject(String jsonStr, TypeReference<T> typeReference) {
        try {
            return objectMapper.readValue(jsonStr, typeReference);
        } catch (JsonProcessingException e) {
            log.error("json parse err,json:{}", jsonStr, e);
            throw new RuntimeException(e);
        }
    }

    public static String toJsonStr(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("json字符串转java对象失败:{}", obj, e);
            throw new RuntimeException(e);
        }
    }
}
